<?php
/**
 * Created by PhpStorm.
 * User: server
 * Date: 2018/6/11
 * Time: 16:33
 */

namespace app\common\model;
require_once EXTEND_PATH."/MfwApi/Openapi.php";
require_once EXTEND_PATH."/MfwApi/OrderSyn.php";
use think\Db;

class MfwApi
{
    public function get_sku_info($sku_id){

        //调用接口的动作
        $action = 'sales.sku.info.get';

        /*
         * 业务请求数据,非加密数据 type: array
         */
        $data = [];
        $data['sku_id'] = $sku_id;
//        $data['page_size'] = 20;


        //获取accesstoken
        $objAccessToken = new \MSDK_Php_AccessToken();
        $objAccessToken->getAccessToken();


        //发送请求
        $obj = new \MSDK_Php_Openapi();

        if(false == $obj->send($action, $data)){

            logs("get_sku_info_erro",$obj);

        }else{

            //获取订单列表
            $mfw_sku = $this->object_array($obj->getData());
            if($mfw_sku['sku_id']){
                $old_mfw_sku=Db::name('mfw_sku')->where('sku_id',$mfw_sku['sku_id'])->find();
                if($old_mfw_sku){
                    $sku_id=$mfw_sku['sku_id'];
                    unset($mfw_sku['sku_id']);
                    Db::name('mfw_sku')->where('sku_id',$sku_id)->update($mfw_sku);
                }else{

                    Db::name('mfw_sku')->insert($mfw_sku);
                }
            }
            return mfw_sku;
        }
    }
    function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }
    public function order_list_get($data){

        //调用接口的动作
        $action = 'sales.order.list.get';

        /*
         * 业务请求数据,非加密数据 type: array
         */
//        $data = [];
//        $data['page_no'] = 1;
//        $data['page_size'] = 20;


        //获取accesstoken
        $objAccessToken = new \MSDK_Php_AccessToken();
        $objAccessToken->getAccessToken();


        //发送请求
        $obj = new \MSDK_Php_Openapi();

        if(false == $obj->send($action, $data)){
            dump($obj);

        }else{

            //获取订单列表
            $result = $obj->getData();
            logs('get_mfw_order', date('Y-m-d H:i:s', time()));
            logs('get_mfw_order', $result);
            $list = $result['list'];
            foreach($list as $k=>$v){
                $count = 0;

                $insert['data']=json_encode($v);
                $insert['order_id'] = $v['orderId'];
                $insert['order_status'] = $v['status']['orderStatus'];
                $insert['refund_status'] = $v['status']['refundStatus'];
                $insert['all_refund_flag'] = $v['status']['allRefundFlag'];
                $insert['go_date'] = strtotime($v['goDate']);
                $insert['end_date'] = strtotime($v['endDate']);
                $insert['paytime'] = strtotime($v['paytime']);
                $insert['ctime'] = strtotime($v['ctime']);
                $insert['sales_id'] = $v['salesId'];
                $insert['sales_name'] = $v['salesName'];
                $insert['ota_sales_name'] = $v['otaSalesName'];
                $insert['sales_type'] = $v['salesType'];
                $insert['mdd'] = $v['mdd'];
                $insert['from'] = $v['from'];
                $insert['sku_id'] = $v['skuId'];
                $insert['ota_sku_id'] = $v['otaSkuId'];
                $insert['sku_name'] = $v['skuName'];
                $insert['total_price'] = $v['totalPrice'];
                $insert['payment_fee'] = $v['paymentFee'];
                $insert['items'] = json_encode($v['items'],JSON_UNESCAPED_UNICODE);
                $insert['promotion_detail'] = json_encode($v['promotionDetail'],JSON_UNESCAPED_UNICODE);
                $insert['skus'] = json_encode($v['skus'],JSON_UNESCAPED_UNICODE);

                //预订人信息
                $mfw_booking_people=$v['bookingPeople'];
                $mfw_booking_people['mfw_order_id']=$v['orderId'];


//                $insert['trip'] = '出行信息';
//                $insert['ts_address'] = '取还地址';
//                $insert['address'] = '地址';
                $insert['ischeck'] = false;
                $insert['update_time'] =time();

                $res1 = Db::name('mfw_booking_people') -> where('mfw_order_id',$insert['order_id']) -> find();
                if(!$res1){

                    $insert['mfw_booking_people_id'] =Db::name('mfw_booking_people')->insertGetId($mfw_booking_people);
                }else{

                    Db::name('mfw_booking_people')->where('mfw_order_id',$insert['order_id'])-> update($mfw_booking_people);

                }

                $res = Db::name('mfw_order') -> where('order_id',$insert['order_id']) -> find();
                if($res){
                    Db::name('mfw_order')  -> where('order_id',$insert['order_id'])-> update($insert);
                }else{
                    $insert['create_time'] =time();
                    Db::name('mfw_order') -> insert($insert);
                }
                $count++;
            }
            return $count;
        }
    }
    public function order_detail_get($order_id){

        //调用接口的动作
        $action = 'sales.order.detail.get';

        /*
         * 业务请求数据,非加密数据 type: array
         */
        $data = [];
        $data['order_id'] = $order_id;



        //获取accesstoken
        $objAccessToken = new \MSDK_Php_AccessToken();
        $objAccessToken->getAccessToken();


        //发送请求
        $obj = new \MSDK_Php_Openapi();

        if(false == $obj->send($action, $data)){
            dump($obj);

        }else{

            //获取订单列表
            $result = $obj->getData();
            $v=$result;
            logs('sales.order.detail.get', date('Y-m-d H:i:s', time()));
            logs('sales.order.detail.get', $result);
            $count = 0;
            $insert['data']=json_encode($v);
            $insert['order_id'] = $v['orderId'];
            $insert['order_status'] = $v['status']['orderStatus'];
            $insert['refund_status'] = $v['status']['refundStatus'];
            $insert['all_refund_flag'] = $v['status']['allRefundFlag'];
            $insert['go_date'] = strtotime($v['goDate']);
            $insert['end_date'] = strtotime($v['endDate']);
            $insert['paytime'] = strtotime($v['paytime']);
            $insert['ctime'] = strtotime($v['ctime']);
            $insert['sales_id'] = $v['salesId'];
            $insert['sales_name'] = $v['salesName'];
            $insert['ota_sales_name'] = $v['otaSalesName'];
            $insert['sales_type'] = $v['salesType'];
            $insert['mdd'] = $v['mdd'];
            $insert['from'] = $v['from'];
            $insert['sku_id'] = $v['skuId'];
            $insert['ota_sku_id'] = $v['otaSkuId'];
            $insert['sku_name'] = $v['skuName'];
            $insert['total_price'] = $v['totalPrice'];
            $insert['payment_fee'] = $v['paymentFee'];
            $insert['items'] = json_encode($v['items'],JSON_UNESCAPED_UNICODE);
            $insert['promotion_detail'] = json_encode($v['promotionDetail'],JSON_UNESCAPED_UNICODE);
            $insert['skus'] = json_encode($v['skus'],JSON_UNESCAPED_UNICODE);

            //预订人信息
            $mfw_booking_people=$v['bookingPeople'];
            $mfw_booking_people['mfw_order_id']=$v['orderId'];
//                $insert['trip'] = '出行信息';
//                $insert['ts_address'] = '取还地址';
//                $insert['address'] = '地址';
            $insert['ischeck'] = false;
            $insert['update_time'] =time();
            $res1 = Db::name('mfw_booking_people') -> where('mfw_order_id',$insert['order_id']) -> find();
            if(!$res1){

                $insert['mfw_booking_people_id'] =Db::name('mfw_booking_people')->insertGetId($mfw_booking_people);
            }else{

                Db::name('mfw_booking_people')->where('mfw_order_id',$insert['order_id'])-> update($mfw_booking_people);
            }
            $res = Db::name('mfw_order') -> where('order_id',$insert['order_id']) -> find();
            if($res){
                Db::name('mfw_order')  -> where('order_id',$insert['order_id'])-> update($insert);
            }else{
                $insert['create_time'] =time();
                Db::name('mfw_order') -> insert($insert);
            }


            return $insert;
        }
    }


    public function order_traveler_get($order_id){

        //调用接口的动作
        $action = 'sales.order.traveler.get';

        //获取accesstoken
        $objAccessToken = new \MSDK_Php_AccessToken();
        $objAccessToken->getAccessToken();
        $data['order_id']=$order_id;
//        dump($order_id);
        //发送请求
        $obj = new \MSDK_Php_Openapi();
        if(false == $obj->send($action, $data)){

            dump($obj->getError());
        }else{

            $result = $obj->getData();
            if($result['travel_people']['traveler']){
//                dump($result);
                $travelers=[];
                foreach ($result['travel_people']['traveler'] as $key=>$traveler){
                    $result['travel_people']['traveler'][$key]['order_id']=$order_id;
                    $traveler=[];
                    $traveler['name']=$result['travel_people']['traveler'][$key]['name'];
                    $traveler['phone']=$result['travel_people']['traveler'][$key]['cellphone'];
                    $traveler['id_card']=$result['travel_people']['traveler'][$key]['order_id'];
                    $travelers[]=$travelers;
                }
                $mfw_traveler=Db::name('mfw_traveler')->where("order_id","order_id")->find();
                if(!$mfw_traveler){
                    Db::name('mfw_traveler')  ->insertAll($result['travel_people']['traveler']);
                    Db::name('order_traveler')  ->insertAll($travelers);
                }

            }else{
//                dump("没有信息");

            }


            //未完成数据库写入！！！！！！！！！！！！！！！！！！
        }
    }

    public function refund_list_get($data){

        //调用接口的动作
        $action = 'sales.refund.list.get';

        //获取accesstoken
        $objAccessToken = new \MSDK_Php_AccessToken();
        $objAccessToken->getAccessToken();

        //发送请求
        $obj = new \MSDK_Php_Openapi();
        if(false == $obj->send($action, $data)){
            $msg = '接口调用失败';
            $this->_display($msg, $obj->getError(), $obj->getErrno());
        }else{
            $msg = '接口调用成功';
            $result = $obj->getData();
            $list = $result['list'];
            foreach($list as $k=>$v){
                $count = 0;
                $insert['data']=json_encode($v);
                $insert['refund_id'] = $v['refund_id'];
                $insert['order_id'] = $v['order_id'];
                $insert['apply_ctime'] = strtotime($v['apply_ctime']);
                $insert['update_time'] = strtotime($v['update_time']);
                $insert['apply_reason'] = $v['apply_reason'];
                $insert['refund_flag'] = $v['refund_flag'];
                $insert['refund_fee'] = $v['refund_fee'];
                $insert['total_price'] = $v['total_price'];
                $insert['refund_remark'] = json_encode($v['refund_remark'],JSON_UNESCAPED_UNICODE);//
                $insert['payment_fee'] = $v['payment_fee'];
                $insert['refunded_items'] = json_encode($v['refunded_items'],JSON_UNESCAPED_UNICODE);//
                $insert['refunding_items'] = json_encode($v['refunding_items'],JSON_UNESCAPED_UNICODE);//
                $insert['items'] = json_encode($v['items'],JSON_UNESCAPED_UNICODE);//
                $insert['ischeck'] = false;
                $res = Db::name('mfw_order_refund') -> where('refund_id',$v['refund_id']) -> find();
                if($res){
                    Db::name('mfw_order_refund') -> where('refund_id',$v['refund_id'])-> update($insert);
                }else{
                    $count++;
                    $insert['create_time'] =time();
                    Db::name('mfw_order_refund') -> insert($insert);
                }

                $this->order_detail_get($insert['order_id']);
            }
            return $count;

        }
    }

    public function push_order_sync(){


        //获取订单
        $result =input();
//            $result = array (
//                '/admin/Mfw_demo/push_order_sync' => '',
//                'partnerId' => '11202',
//                'action' => 'push.order.sync',
//                'timestamp' => '1529226779',
//                'nonce' => 'M3IRLA3ialfVakpc',
//                'data' => 'CpX8Lhn5az5Qu7Z9JFiIplO8qF+QfquUcfQZF2zm0t1NiITPOy0JNmMyfSGE8ifR/mn8qWDFZfPTIK0Uz5VBTa1aWmvJZiCht+TEndaABET6X03DvKfz81ArBv21uB8mCIbJ7fG1TRB//9Py0BchpmjMIjusYKLLOA4e+Feu1rIYL0vDZYttogrmjSWBNUTixNf8++VszQeeaLdoejLjuk/X1hW4GxQTVxaIYoHHY8IgsJAnlfmWROWJ9Q4r7RcN1XHn3JhhF8bN09v/4rpxwfdrJeCkp+inqHxLVIxdjEeYrgVSRhBULMgxNMpyJbIx5/GLYv4L0VWrHc9CHSKm9LPLtaxWivW3kDBAL2H+FqaJHpRwJv//kj1zPmCi38CYVxxGXyQsaqpKQnm1lRTJ6YQ1Zj3ExZS0si93HrApMU4B73nosso1hwSVes++2AYBexxz7ACsPh73giDsuC0w2rgj/bQx6VBL1AeEseBdHKhgwPU0PKghAV3kABtilBlHdmxtXjviuguFm00Qty7Iq0jNQVPGSv0o9kXmdk+o7h9GNl+GA6muDbhiZcoHjBzAo5nkJDZMwKk55ohfJScHtwfhD1pDuaQUAg9bDwDrCz8H5F0BLnCv6a1wh94vWfNj+3HekZbv0hzv3tbVcWeIF9nxtrl159qZPLNrET1IXDQNOAvNyrjUP9hUJuxu2rrmA5nnTYMDZY1mgULV2Ra3UTWiCdWNmc38uH70LfuRgSjGFUqnGkmEJU0XrlTsyX9XqsOEDYt04bgNS5GkaN50QTrquMIrDRK+C2cvPFhn1/1Dy+n6DotZu6FGSXKtyirSYQMxlevROQIlBwIHzIHm8nTlVXx5f9TdCd1tydn2D2x9Kn7EZKGJDga4k6PBO3jQxd93Dd9nKA1YYrphYtMgD3cy+w/K0PC6PZvkigQhwZeS2b+ZMF0c1KcC+Di39lyyMR8SU6I9oujRHHIUw4INYusPOqVwWXQfUOVNp0QEp6/gGgdLYyZG04pYOdVVRV5h5DnKM7gq8TFWt3xTD755rREwNru0b7oydkf7PDpFr4LcR89NTROQxux9B1Sus8RqWhxtiBWvEELtIf9VhRSq7555qoPTumrlpDXSci4RoJ/rlOTPdwhRVH7l/hJuULSBbhkmDTyZ2KRhVnrYirtJ7TYc2Bxv4nJbNLG6SVUBSywYx1x/tAxTKQIOtIVVVTw3use8DPRWCMgO/7pYoYE4qpX+f+o6OhDM2RWchLdhWPWmgJXCpUziIEZBiZcSdhbJFvAaluGdotmqJcks1X6VDcsqs0m8ky++sDr92lsANH6oCzCeKz429pJp56bZySaBk4TwMfgXPL2t46nmSAKlrmAl+egc9XeMAy3ZKnXXf6kQhusd3mlTKOTW+Ddr1IbvGLB/wAj6m9SESbLTAWf+Sp/qP0oOXSMT+kGL1buPiTAZ3wLrGa1+fMMQkY/JKxu3cZBHjV9d7zClYFuw8WDeDj3fuPCSNSfOp+fYkhBF1BctNaI4MXKpt/u98qMsgQxzVLkrJ9XUE3pJF3naHPtkm3bcfzh1PZaw7FXl2gqAyHWmhccYCyfDJKp5swvVOGywJMmMibg6On2BtFDrVyQX5s7eV0GzDBKAblDtS1aJ13nV+bxzddPWVyLFwMXxl/nfMxpMM1nmYTGOB3Cm8THWpXxJQ1plcfoSpxoDEQSH+EeI40R70lkahc3I9sQZgRvGdoQyjFdx6Oj+sG/6z5fnVk64lWsh3fgPAz6XNIWc0/k+VyS/MxHft/r/okn1xFEPypupTl9BMb91qDmwhGsyDl+tPfIhijvqbJkpTksH82kud8SIS4n3AWzO4Zb7oiUM7fcLMmawAfVurH4fsXr+IoXqe+jbYk8RJaKf1aDbpkgZwkd5M7Ppd4O57ur+tVsf',
//                'sign' => '3a7050608d83a2c0336866710dcd338d',
//            );
        logs("push_order_sync_test","start");
        logs("push_order_sync_test",$result);
        logs("push_order_sync_test","end");
        /*
     * ===============================php接收请求数据======================================
     */
        $postData = $result; //马蜂窝请求数据（表单数据包括：partnerId, data等）,不同系统获取数据方式不同

        /*
         *  实例化接收数据类
         */


        $obj = new \MSDK_Php_OrderSyn();
        $obj->checkAuth($postData);
        $data = $obj->getData();
        logs("push_order_sync_data",$data);
//        $data=array (
//            'order_id' => '3279152021082828952966',
//            'status' => 11,
//            'info' =>
//                array (
//                    'data' =>
//                        array (
//                            'items' =>
//                                array (
//                                    0 =>
//                                        array (
//                                            'name' => '成人',
//                                            'remain_num' => 2,
//                                            'remain_payment_fee' => 2700,
//                                            'price' => 1360,
//                                            'skuId' => 72190774,
//                                            'id' => 49380482,
//                                            'num' => 2,
//                                            'total_price' => 2720,
//                                            'payment_fee' => 2700,
//                                            'price_type' => 8,
//                                        ),
//                                ),
//                            'refunding_items' =>
//                                array (
//                                    0 =>
//                                        array (
//                                            'id' => 49380482,
//                                            'name' => '成人',
//                                            'num' => 0,
//                                            'refund_sold' => '604.44',
//                                            'refund_fee' => '600.00',
//                                        ),
//                                ),
//                            'refunded_items' =>
//                                array (
//                                ),
//                            'refund_remark' =>
//                                array (
//                                    0 =>
//                                        array (
//                                            'action' => 'apply',
//                                            'remark' => '',
//                                            'uid' => 37468098,
//                                            'ctime' => '2021-10-08 16:10:40',
//                                        ),
//                                ),
//                            'travelers' =>
//                                array (
//                                ),
//                            'refunding_travelers' =>
//                                array (
//                                ),
//                            'refunded_travelers' =>
//                                array (
//                                ),
//                            'order_id' => '3279152021082828952966',
//                            'total_price' => '2720.00',
//                            'payment_fee' => '2700.00',
//                            'refund_fee' => '0.00',
//                            'refund_flag' => 2,
//                            'refund_id' => 5446754,
//                            'apply_ctime' => '2021-10-08 16:10:40',
//                            'update_time' => '2021-10-08 16:10:40',
//                            'apply_reason' => 20,
//                        ),
//                ),
//            'nonce' => 'pUP2Z2c1qvdWbpph',
//        );
//解析失败直接返回失败
        if(empty($data)){
            echo $obj->getReturn(false, '数据解密失败'); //失败的返回方法
            exit;
        }
        /*
        * ==========================合作商家内部逻辑处理=================================
        */
        switch ($data['status']){   //订单状态同步动作  actionDesc 为推送动作描述

            case \MSDK_Php_Const::ORDER_STATUS_CREATE:            //创建订单
                $actionDesc = \MSDK_Php_Const::$ORDER_STATUS_MAP[\MSDK_Php_Const::ORDER_STATUS_CREATE];
                //$this->save_syn_order($data);
                break;

            case \MSDK_Php_Const::ORDER_STATUS_PAID:              //支付成功(待出单)
                $actionDesc = \MSDK_Php_Const::$ORDER_STATUS_MAP[\MSDK_Php_Const::ORDER_STATUS_CREATE];
                $this->save_syn_order($data);
                break;

            case \MSDK_Php_Const::ORDER_STATUS_ISSUE:             //供应商已出单
                $actionDesc = \MSDK_Php_Const::$ORDER_STATUS_MAP[\MSDK_Php_Const::ORDER_STATUS_ISSUE];
                $this->save_syn_order($data);
                break;

            case \MSDK_Php_Const::ORDER_STATUS_COMPLETE:          //订单已完成
                $actionDesc = \MSDK_Php_Const::$ORDER_STATUS_MAP[\MSDK_Php_Const::ORDER_STATUS_COMPLETE];
                $this->save_syn_order($data);
                break;

            case \MSDK_Php_Const::ORDER_STATUS_CLOSE:             //订单已关闭
                $actionDesc = \MSDK_Php_Const::$ORDER_STATUS_MAP[\MSDK_Php_Const::ORDER_STATUS_CLOSE];
                $this->save_syn_order($data);
                break;

            case \MSDK_Php_Const::ORDER_STATUS_REFUND_APPLY:      //已申请退款
                $actionDesc = \MSDK_Php_Const::$ORDER_STATUS_MAP[\MSDK_Php_Const::ORDER_STATUS_REFUND_APPLY];
                $this->save_syn_order($data);
//                $this->save_syn_refund_order($data);
                break;

            case \MSDK_Php_Const::ORDER_STATUS_REFUND_CONFIRM:    //已确认退款
                $actionDesc = \MSDK_Php_Const::$ORDER_STATUS_MAP[\MSDK_Php_Const::ORDER_STATUS_REFUND_CONFIRM];
//                $this->save_syn_refund_order($data);
                $this->save_syn_order($data);
                break;

            case \MSDK_Php_Const::ORDER_STATUS_REFUND_COMPLETE:   //已完成退款
                $actionDesc = \MSDK_Php_Const::$ORDER_STATUS_MAP[\MSDK_Php_Const::ORDER_STATUS_REFUND_COMPLETE];
//                $this->save_syn_refund_order($data);
                $this->save_syn_order($data);
                break;

            case \MSDK_Php_Const::ORDER_STATUS_REFUND_REFUSED:    //已拒绝退款
                $actionDesc = \MSDK_Php_Const::$ORDER_STATUS_MAP[\MSDK_Php_Const::ORDER_STATUS_REFUND_REFUSED];
//                $this->save_syn_refund_order($data);
                $this->save_syn_order($data);
                break;

            case \MSDK_Php_Const::ORDER_STATUS_TRAVEL_USER:       //用户填写出行人信息
                $actionDesc = \MSDK_Php_Const::$ORDER_STATUS_MAP[\MSDK_Php_Const::ORDER_STATUS_TRAVEL_USER];
                $this->save_syn_order($data);
                break;

            case \MSDK_Php_Const::ORDER_STATUS_TRAVEL_AUDIT:      //商家seller后台更新
                $actionDesc = \MSDK_Php_Const::$ORDER_STATUS_MAP[\MSDK_Php_Const::ORDER_STATUS_TRAVEL_AUDIT];
                $this->save_syn_order($data);
                break;

            default:
                echo $obj->getReturn(false, $obj->getError()); //失败的返回方法
                exit;
                break;
        }
        /*
         * ==========================返回给马蜂窝=================================
         */

        echo $obj->getReturn(true); //成功的返回方法
        exit;




    }
    public function save_syn_order($data){
        $order_id = $data['order_id'];
        $mfwObj = new \MSDK_Php_Openapi();
        $action = 'sales.order.detail.get'; // 调用接口
        $data = [];
        $data['order_id'] = $order_id;
        if($mfwObj->send($action, $data)){
            $result = $mfwObj->getData();
//            dump($result);
            if (!empty($result)){
                $find = Db::name('mfw_booking_people')->where('mfw_order_id',$result['orderId'])->find();
                $saveData = [];
                $people = [];
                if (!empty($result['bookingPeople'])){
                    $people = [
                        'uid' => $result['bookingPeople']['uid'],
                        'name' => $result['bookingPeople']['name'],
                        'email' => $result['bookingPeople']['email'],
                        'mfw_order_id' => $result['orderId'],
                        'phone_area' => $result['bookingPeople']['phone_area'],
                        'phone' => $result['bookingPeople']['phone'],
                        'wechat' => $result['bookingPeople']['wechat'],
                        'remark' => $result['bookingPeople']['remark'],
                    ];
                }

                if ($find){
                    $mfw_booking_people_id =$find['id'];
                    Db::name('mfw_booking_people')->where('id', $mfw_booking_people_id)->strict(false)->update($people);
                }else{
                    $mfw_booking_people_id = Db::name('mfw_booking_people')->strict(false)->insertGetId($people);
                }
                $saveData['order_id'] = $result['orderId'];
                $saveData['order_status'] = $result['status']['orderStatus'];
                $saveData['refund_status'] = $result['status']['refundStatus'];
                $saveData['all_refund_flag'] = $result['status']['allRefundFlag'];
                $saveData['go_date'] = ($result['goDate'] == '0000-00-00')?'':strtotime($result['goDate']);
                $saveData['end_date'] = ($result['endDate'] == '0000-00-00')?'':strtotime($result['endDate']);
                $saveData['paytime'] = ($result['paytime'] == '0000-00-00')?'':strtotime($result['paytime']);
                $saveData['ctime'] = ($result['ctime'] == '0000-00-00')?'':strtotime($result['ctime']);
                $saveData['mfw_booking_people_id'] = $mfw_booking_people_id;
                $saveData['sales_id'] = $result['salesId'];
                $saveData['sales_name'] = $result['salesName'];
                $saveData['ota_sales_name'] = $result['otaSalesName'];
                $saveData['sales_type'] = $result['salesType'];
                $saveData['mdd'] = $result['mdd'];
                $saveData['from'] = $result['from'];
                $saveData['sku_id'] = $result['skuId'];
                $saveData['ota_sku_id'] = $result['otaSkuId'];
                $saveData['sku_name'] = $result['skuName'];
                $saveData['total_price'] = $result['totalPrice'];
                $saveData['payment_fee'] = $result['paymentFee'];
                $saveData['create_time'] = time();
                $saveData['items'] = json_encode($result['items'],JSON_UNESCAPED_UNICODE);
                $saveData['promotion_detail'] = json_encode($result['promotionDetail'],JSON_UNESCAPED_UNICODE);
                $saveData['skus'] = json_encode($result['skus'],JSON_UNESCAPED_UNICODE);
                $saveData['data'] = json_encode($result,JSON_UNESCAPED_UNICODE);

                // 存进数据表
                $find = Db::name('mfw_order')->where('order_id',$saveData['order_id'])->find();
                if ($find){
                    Db::name('mfw_order')->where('order_id',$saveData['order_id'])->strict(false)->update($saveData);
                }else{
                    Db::name('mfw_order')->strict(false)->insert($saveData);
                }
                // 把马蜂窝的订单同步到订单表中
                $saveData['people'] = $result['bookingPeople'];
                $saveData['reduce_ota'] = $result['promotionDetail']['reduce_ota'];
                $saveData['reduce_mfw'] = $result['promotionDetail']['reduce_mfw'];
                self::saveOrder($saveData);
//                dump($saveData);
                $this->order_traveler_get($saveData['order_id']);
                if($saveData['refund_status']==4){
                    Db::name('order')
                        ->where('order_id', $saveData['order_id'])
                        ->setField('dispose_status', 'error');

                    // 订单下旅客设置为异常
                    Db::name('order_traveler')
                        ->alias('ot')
                        ->join('order o', 'o.id=ot.oid', 'left')
                        ->where('o.order_id', $saveData['order_id'])
                        ->field('ot.*')
                        ->setField('ot.is_error', 1);
                }

                return true;
            }
        }

        return false;
    }
    /**
     *  同步订单
     */
    public static function saveOrder($data = [])
    {
        if (!empty($data)){
            $saveData = [];
            $saveData['order_id'] = $data['order_id'];
            // 订单状态：1-待支付，2-待出单，4-已出单，5-已完成，6-已关闭
            switch ($data['order_status']){
                case 1 : $saveData['order_status'] = 'pay_for'; break;
                case 2 : $saveData['order_status'] = 'pending'; break;
                case 4 : $saveData['order_status'] = 'issue'; break;
                case 5 : $saveData['order_status'] = 'finish'; break;
                case 6 : $saveData['order_status'] = 'close'; break;
                default : $saveData['order_status'] = 'pay_for';
            }
            if ($data['all_refund_flag']){
                $saveData['isrefund'] = 1; //1 未全部退款 2 已全部退款
            }else{
                $saveData['isrefund'] = 0;// 0 无退款
            }
            // 1-已完成退款 2-已申请退款 3-拒绝退款 4-已确认退款 0-可发起退款
            switch ($data['refund_status']) {
                case 1: $saveData['refund_status'] = 'refunded'; break;
                case 2: $saveData['refund_status'] = 'check'; break;
                case 3: $saveData['refund_status'] = 'rejected'; break;
                case 4: $saveData['refund_status'] = 'refunding'; break;
                default: $saveData['refund_status'] = '';
            }
            $saveData['money'] = $data['payment_fee'];
            $saveData['title'] = $data['sales_name'];
            $saveData['platform'] = 'mfw';
            $saveData['start_time'] =$data['go_date'];
            $saveData['end_time'] =$data['end_date'];
            $saveData['booking_people_name'] =$data['people']['name'];
            $saveData['booking_people_email'] =$data['people']['email'];
            $saveData['booking_people_phone'] =$data['people']['phone'];
            $saveData['booking_people_wechat'] =$data['people']['wechat'];
            $saveData['booking_people_remark'] =$data['people']['remark'];
            $saveData['booking_people_phone_area'] =$data['people']['phone_area'];
            $saveData['uid'] =$data['people']['uid'];
            $saveData['sales_id'] =$data['sales_id'];
            $saveData['ctime'] =$data['ctime'];
            $saveData['sku_id'] =$data['sku_id'];
            $saveData['sales_name'] =$data['sales_name'];
            $saveData['sku_name'] =$data['sku_name'];
            $saveData['total_price'] =$data['total_price'];
            $saveData['payment_fee'] =$data['payment_fee'];
            $saveData['reduce_ota'] =$data['reduce_ota'];
            $saveData['reduce_mfw'] =$data['reduce_mfw'];
            $saveData['ota_sales_name'] =$data['ota_sales_name'];
            $saveData['dispose_status'] ='no_contact';

            //同步路线
            $route_category=Db::name('route_category')->where('name','马蜂窝')->find();
            $route_product=Db::name('route_product')->where('product_id','in',$saveData['sales_id'])->whereOr('product_id','in',$saveData['sku_id'])->find();
            $route_id=$route_product['route_id'];
            if($route_id){
                $saveData['route_id']=$route_id;
            }
            // 保存到订单表
            $find = Db::name('order')->where('order_id',$saveData['order_id'])->find();
            if ($find){
                Db::name('order')->where('order_id',$saveData['order_id'])->strict(false)->update($saveData);
            }else{
                Db::name('order')->strict(false)->insert($saveData);
            }


        }
    }
    public function save_syn_refund_order($data){
        $v=$data['info']['data'];
        $insert['data']=json_encode($data);
        $insert['refund_id'] = $v['refund_id'];
        $insert['order_id'] = $v['order_id'];
        $insert['apply_ctime'] = strtotime($v['apply_ctime'])< 0?0:strtotime($v['apply_ctime']);;
        $insert['update_time'] = strtotime($v['update_time'])< 0?0:strtotime($v['update_time']);;
        $insert['apply_reason'] = $v['apply_reason'];
        $insert['refund_flag'] = $v['refund_flag'];
        $insert['refund_fee'] = $v['refund_fee'];
        $insert['total_price'] = $v['total_price'];
        $insert['refund_remark'] = json_encode($v['refund_remark'],JSON_UNESCAPED_UNICODE);//
        $insert['payment_fee'] = $v['payment_fee'];
        $insert['refunded_items'] = json_encode($v['refunded_items'],JSON_UNESCAPED_UNICODE);//
        $insert['refunding_items'] = json_encode($v['refunding_items'],JSON_UNESCAPED_UNICODE);//
        $insert['items'] = json_encode($v['items'],JSON_UNESCAPED_UNICODE);//
        $insert['ischeck'] = false;
        $res = Db::name('mfw_order_refund') -> where('refund_id',$v['refund_id']) -> find();
        if($res){
            Db::name('mfw_order_refund') -> where('refund_id',$v['refund_id'])-> update($insert);
        }else{

            $insert['create_time'] =time();
            Db::name('mfw_order_refund') -> insert($insert);
        }
        $this->order_detail_get($insert['order_id']);
    }

    function _display($msg, $error, $errno = 0, $data = null)
    {
        echo sprintf('%s[%s] %s, errno[%s] error[%s], data[%s]' . PHP_EOL, str_repeat('=', 80) . PHP_EOL,
            date('Y-m-d H:i:s',time()), $msg, $errno, $error, json_encode($data,JSON_UNESCAPED_UNICODE));
    }


}